<template>
  <div class="employee-management">
    <div class="header">
      <h2>员工管理</h2>
      <button @click="$router.push('/dashboard')" class="back-btn">返回首页</button>
    </div>
    
    <!-- 添加员工表单 -->
    <div class="add-employee-form">
      <input v-model="newEmployee.name" placeholder="员工姓名" />
      <input v-model="newEmployee.phone" placeholder="联系电话" />
      <select v-model="newEmployee.position">
        <option value="">选择职位</option>
        <option value="cashier">收银员</option>
        <option value="manager">店长</option>
        <option value="stock_keeper">库存管理员</option>
        <option value="other">其他</option>
      </select>
      <select v-model="newEmployee.store_id">
        <option value="">选择所属门店</option>
        <option v-for="store in stores" :key="store.id" :value="store.id">
          {{ store.name }}
        </option>
      </select>
      <input type="date" v-model="newEmployee.hire_date" placeholder="入职日期" />
      <button @click="addEmployee" :disabled="!isValidEmployee">添加员工</button>
    </div>

    <!-- 员工列表 -->
    <table class="employee-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>姓名</th>
          <th>电话</th>
          <th>职位</th>
          <th>所属门店</th>
          <th>入职日期</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="employee in employees" :key="employee.id">
          <td>{{ employee.id }}</td>
          <td>{{ employee.name }}</td>
          <td>{{ employee.phone }}</td>
          <td>{{ getPositionName(employee.position) }}</td>
          <td>{{ getStoreName(employee.store_id) }}</td>
          <td>{{ formatDate(employee.hire_date) }}</td>
          <td>
            <span :class="['status-badge', employee.status === 'active' ? 'active' : 'inactive']">
              {{ employee.status === 'active' ? '在职' : '离职' }}
            </span>
          </td>
          <td>
            <button @click="editEmployee(employee)">编辑</button>
            <button 
              @click="toggleEmployeeStatus(employee)"
              :class="['status-btn', employee.status === 'active' ? 'leave' : 'join']"
            >
              {{ employee.status === 'active' ? '离职' : '入职' }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 编辑员工对话框 -->
    <div v-if="showEditDialog" class="edit-dialog">
      <div class="edit-dialog-content">
        <h3>编辑员工</h3>
        <div class="form-group">
          <label>员工姓名：</label>
          <input v-model="editingEmployee.name" />
        </div>
        <div class="form-group">
          <label>联系电话：</label>
          <input v-model="editingEmployee.phone" />
        </div>
        <div class="form-group">
          <label>职位：</label>
          <select v-model="editingEmployee.position">
            <option value="">选择职位</option>
            <option value="cashier">收银员</option>
            <option value="manager">店长</option>
            <option value="stock_keeper">库存管理员</option>
            <option value="other">其他</option>
          </select>
        </div>
        <div class="form-group">
          <label>所属门店：</label>
          <select v-model="editingEmployee.store_id">
            <option value="">选择所属门店</option>
            <option v-for="store in stores" :key="store.id" :value="store.id">
              {{ store.name }}
            </option>
          </select>
        </div>
        <div class="form-group">
          <label>入职日期：</label>
          <input type="date" v-model="editingEmployee.hire_date" />
        </div>
        <div class="dialog-buttons">
          <button @click="updateEmployee">保存</button>
          <button @click="showEditDialog = false" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'EmployeeManagement',
  data() {
    return {
      employees: [],
      stores: [],
      newEmployee: {
        name: '',
        phone: '',
        position: '',
        store_id: '',
        hire_date: '',
        status: 'active'
      },
      showEditDialog: false,
      editingEmployee: null
    }
  },
  computed: {
    isValidEmployee() {
      return this.newEmployee.name && 
             this.newEmployee.phone && 
             this.newEmployee.position && 
             this.newEmployee.hire_date
    }
  },
  created() {
    this.fetchEmployees()
    this.fetchStores()
  },
  methods: {
    getPositionName(position) {
      const positions = {
        'cashier': '收银员',
        'manager': '店长',
        'stock_keeper': '库存管理员',
        'other': '其他'
      }
      return positions[position] || position
    },
    getStoreName(storeId) {
      const store = this.stores.find(s => s.id === storeId)
      return store ? store.name : '未分配'
    },
    formatDate(date) {
      if (!date) return '未设置'
      return new Date(date).toLocaleDateString()
    },
    async fetchStores() {
      try {
        const response = await axios.get('/api/stores', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.stores = response.data
      } catch (error) {
        console.error('获取门店列表失败:', error)
        alert('获取门店列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async fetchEmployees() {
      try {
        const response = await axios.get('/api/employees', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.employees = response.data
      } catch (error) {
        console.error('获取员工列表失败:', error)
        alert('获取员工列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async addEmployee() {
      if (!this.isValidEmployee) {
        alert('请填写完整的员工信息')
        return
      }
      try {
        const employeeData = {
          ...this.newEmployee,
          status: 'active'
        }
        console.log('添加员工数据:', employeeData)
        
        const response = await axios.post('/api/employees', employeeData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchEmployees()
        this.newEmployee = { 
          name: '', 
          phone: '', 
          position: '', 
          store_id: '', 
          hire_date: '',
          status: 'active'
        }
        alert('添加员工成功')
      } catch (error) {
        console.error('添加员工失败:', error)
        alert('添加员工失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    editEmployee(employee) {
      this.editingEmployee = { ...employee }
      this.showEditDialog = true
    },
    async updateEmployee() {
      try {
        const employeeData = {
          ...this.editingEmployee,
          hire_date: this.editingEmployee.hire_date || null,
          status: this.editingEmployee.status
        }
        console.log('更新员工数据:', employeeData)
        
        await axios.put(`/api/employees/${this.editingEmployee.id}`, employeeData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchEmployees()
        this.showEditDialog = false
        alert('更新员工成功')
      } catch (error) {
        console.error('更新员工失败:', error)
        alert('更新员工失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async toggleEmployeeStatus(employee) {
      try {
        const newStatus = employee.status === 'active' ? 'inactive' : 'active'
        console.log('更新员工状态:', { status: newStatus })
        
        await axios.put(`/api/employees/${employee.id}/status`, { 
          status: newStatus 
        }, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        this.fetchEmployees()
        alert(`员工${newStatus === 'active' ? '入职' : '离职'}成功`)
      } catch (error) {
        console.error('更新员工状态失败:', error)
        alert('更新员工状态失败：' + (error.response?.data?.message || '未知错误'))
      }
    }
  }
}
</script>

<style scoped>
.employee-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  padding: 8px 16px;
  background-color: #909399;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-employee-form {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.employee-table {
  width: 100%;
  border-collapse: collapse;
}

.employee-table th,
.employee-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.employee-table th {
  background-color: #f5f5f5;
}

button {
  margin: 0 5px;
  padding: 5px 10px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #66b1ff;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-badge.active {
  background-color: #67c23a;
  color: white;
}

.status-badge.inactive {
  background-color: #f56c6c;
  color: white;
}

.status-btn {
  font-size: 12px;
}

.status-btn.join {
  background-color: #67c23a;
}

.status-btn.leave {
  background-color: #f56c6c;
}

.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit-dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn {
  background-color: #909399;
}

.cancel-btn:hover {
  background-color: #a6a9ad;
}
</style> 